package adnotatio.client.annotator.selection;

import com.google.gwt.user.client.Element;

/**
 * The content selection object providing access to the range of selected words
 * and to the real selected text
 * 
 * @author kotelnikov
 */
public class WordSelection {

    /**
     * The owner of this selection
     */
    private final ActiveHTMLPanel fActiveHTMLPanel;

    /**
     * Position of the first word in the selection
     */
    private int fFirstWordPos = -1;

    /**
     * Position of the last word in the selection
     */
    private int fLastWordPos = -1;

    /**
     * The selection text
     */
    private String fText;

    /**
     * @param panel the owner of this selection
     */
    WordSelection(ActiveHTMLPanel panel) {
        fActiveHTMLPanel = panel;
        TextSelection s = TextSelection.getSelection();
        Element start = s.getStartElement();
        Element end = s.getEndElement();
        String startId = fActiveHTMLPanel.getElementId(start);
        String endId = fActiveHTMLPanel.getElementId(end);
        if (fActiveHTMLPanel.isWordId(startId)
            && fActiveHTMLPanel.isWordId(endId)) {
            int from = fActiveHTMLPanel.getWordPosById(startId);
            int to = fActiveHTMLPanel.getWordPosById(endId);
            fFirstWordPos = Math.min(from, to);
            fLastWordPos = Math.max(from, to);
            fText = s.getText();
        }
    }

    /**
     * @return the position of the first selected word
     */
    public int getFirstWordPos() {
        return fFirstWordPos;
    }

    /**
     * Returns the number of selected words
     * 
     * @return the number of selected words
     */
    public int getLength() {
        return fText != null ? fLastWordPos - fFirstWordPos + 1 : 0;
    }

    /**
     * Returns the real selected text. It can contain only parts of words (in
     * the beginning and at the end).
     * 
     * @return the selected text
     */
    public String getText() {
        return fText;
    }

    /**
     * Returns <code>true</code> if the underlying text has selection
     * 
     * @return <code>true</code> if the underlying text has selection
     */
    public boolean hasSelection() {
        return fText != null;
    }
}